<?php

class	router
{
	private $registry;
	private $path;
	private $args = array();
	public $file;
	
	function __construct($registry)
	{
		$this->registry = $registry;
	}
	
	/**
	*
	* @set the path to the controller
	*
	* @param $path
	*
	* @access private
	*
	* @return void
	*
	*/
	private function setPath($path)
	{
		if (is_dir($path) == false) {
			throw new Exception('invalid controller path: ' . $path);
		}
		$this->path = $path;
	}

	/**
	*
	* @get the right controller from the request
	*
	* @access private
	*
	* @return void
	*
	*/
	private function getController()
	{
		$this->registry->request->getController();
		if (__MODULE == 'true') {
			$this->registry->router->setPath(__SITE_PATH . $this->registry->controller . '/controller');
			$this->file = $this->path . '/' . $this->registry->controller . 'Controller.php';
		} else {
			$this->file = $this->path . '/' . $this->registry->controller . 'Controller.php';
		}
	}

	/**
	*
	* @Load the right controller from getController
	*
	* @return void
	*
	*/
	public function loader()
	{
		$this->getController();
		if (is_readable($this->file) == false) {
			$this->file = $this->path . '/error404.php';
			$this->controller = 'error404';
		}
		include $this->file;
		
		$class = $this->registry->controller . 'Controller';
		$controller = new $class($this->registry);
		
		if (is_callable(array($controller, $this->registry->action)) == false) {
			$action = 'index';
		} else {
			$action = $this->registry->action;
		}
		$controller->$action();
	}
	
}

?>